/**
 * Copyright © 2013 Creativor Studio.
 * About license information, please see LICENSE.txt.
 */
package org.creativor.rayson.client.transport;

import java.io.IOException;

import org.creativor.rayson.client.transport.http.HttpConnection;
import org.creativor.rayson.client.transport.nio.ClientNioConnection;
import org.creativor.rayson.client.transport.nio.NioListener;
import org.creativor.rayson.share.transport.ByteArrayBuffer;
import org.creativor.rayson.share.transport.http.HttpRequest;
import org.creativor.rayson.util.LangUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Implement of {@link HttpConnection}.
 * 
 * @author creativor
 */
class HttpConnectionImpl implements HttpConnection {
	private final long id;
	private final ServerAgent agent;
	private final ClientNioConnection nioConn;
	private static final Logger LOG = LoggerFactory
			.getLogger(HttpConnection.class);

	HttpConnectionImpl(final long id, final ServerAgent agent) {
		this.id = id;
		this.agent = agent;
		nioConn = new NioConnectionWrapper(this, ConnectionPool.getPool(),
				NioListener.getListener());
	}

	@Override
	public void close() {
		this.agent.back(this);
	}

	/**
	 * @return the agent
	 */
	ServerAgent getAgent() {
		return agent;
	}

	/**
	 * @return the id
	 */
	public long getId() {
		return id;
	}

	/**
	 * Open this connection.
	 * 
	 * @throws IOException
	 *             If any IO error occurred.
	 */
	void open() throws IOException {
		nioConn.open();
	}

	@Override
	public void send(final HttpRequest request) throws IOException,
			InterruptedException {
		LangUtil.testNullArgument(request);
		if (LOG.isDebugEnabled())
			LOG.debug("Send request: " + request);
		final ByteArrayBuffer buffer = new ByteArrayBuffer();
		request.writeTo(buffer);
		nioConn.getWriteBuffer().write(buffer.toByteArray());
		nioConn.getWriteBuffer().flush();
	}

	@Override
	public String toString() {
		final StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("id:" + this.id);
		sb.append(", addr:" + this.agent.getAddress());
		sb.append("}");
		return sb.toString();
	}

}
